package cn.wolfcode.luowowo.member.service.impl;

import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AssertUtil;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.mapper.UserInfoMapper;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.redis.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.redis.util.RedisKeys;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.UUID;

@Service
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public List<UserInfo> get() {
        return userInfoMapper.selectAll();
    }

    @Override
    public Boolean checkPhone(String phone) {
        int count = userInfoMapper.selectCountByPhone(phone);
        return count>0;
    }

    @Override
    public void sendVerifyCode(String phone) throws LogicException {
        // checkSendSmsFrequency  检查短信发送频率

        //从redis获取verify_code_vali:phone的时间
            //从工具类中获取FrequencyKey =  verify_code_vali:phone
            String FrequencyKey = RedisKeys.VERIFY_CODE_VALI.getKey(phone);
            String value = userInfoRedisService.getSendSmsFrequency(FrequencyKey);
       //如果不为空就说明一分钟内发送过,抛出自定义异常
            if (value!=null && !value.equals("")){
                throw new LogicException("请不要频繁发送短信验证码,你以为不要钱啊?,一分钟后才能发知不知道?");
            }
        // 如果为空就写入一个
            userInfoRedisService.setSendSmsFrequency(FrequencyKey,RedisKeys.VERIFY_CODE_VALI.getTime());

        //1.创建UUID验证码
        String code =  UUID.randomUUID().toString().replaceAll("-","").substring(0,4);
        //2.将验证码添加到redis里
        System.out.println("你的验证码为"+ code + "请在"+ Consts.VERIFY_CODE_VAI_TIME+"分钟内使用");

        //使用枚举将前缀加手机变成key
        String key = RedisKeys.VERIFY_CODE.getKey(phone);
        userInfoRedisService.setVerifyCode(key,code,RedisKeys.VERIFY_CODE.getTime());
        //3.发送短信
        //this.sendSms(phone,code);
        System.out.println("发送短信成功");
    }

    @Override
    public void userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) throws LogicException {
         //0验证昵称是否为空
        AssertUtil.hasLength(nickname,"昵称号码不能为空");
        //1验证手机号码是否为空,
        AssertUtil.hasLength(phone,"手机号码不能为空");
         //2验证密码是否为空
        AssertUtil.hasLength(password,"密码不能为空");
        //3验证确认密码是否为空
        AssertUtil.hasLength(rpassword,"确认密码不能为空");
        //4验证密码和确认密码是否为空
        AssertUtil.isEquals(password,rpassword,"两次密码不一致");


        //获取redis中的验证码
        String key = "VerifyCode:"+phone;
        String code = userInfoRedisService.getVerifyCode(key);
        if (code==null || !code.equalsIgnoreCase(verifyCode)){
            throw new LogicException("验证码失效或验证码错误");
        }
        //注册
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        userInfo.setPhone(phone);
        userInfo.setHeadImgUrl("/images/default.jpg");
        userInfo.setState(UserInfo.GENDER_SECRET);
        userInfo.setLevel(1);
        userInfo.setPassword(password);
        userInfoMapper.insert(userInfo);
    }

    @Override
    public void sendSms(String phone,String code) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAIb7Bkec6jjk4J", "ZFh1qTZvyM1RKOamuFSonKp5wYgcuu");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "黎嘉荣");
        request.putQueryParameter("TemplateCode", "SMS_141135008");
        request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException ce) {
            ce.printStackTrace();
        }
    }

    @Override
    public String userLogin(String username, String password) throws LogicException {
        //判断账号名和密码是否为空
        AssertUtil.hasLength(username,"账号不能为空");
        AssertUtil.hasLength(password,"密码不能为空");

        //查数据库账号密码是否存在
        UserInfo userInfo = userInfoMapper.selectByUsernameAndPassword(username,password);
        if (userInfo==null){
            throw new LogicException("账号或密码错误");
        }

        //生成一个token(相当于jsessionId)保存用户数据
        String token = UUID.randomUUID().toString().replaceAll("-","");
        String pre_code = RedisKeys.USER_LOGIN.getKey(token);
        String user = JSON.toJSONString(userInfo);
        //通过枚举类获取用户的过期时间
        userInfoRedisService.setToken(pre_code,user,RedisKeys.USER_LOGIN.getTime());

        //返回一个带前缀的token值 相当于jseeionId
        return pre_code;
    }

}

